package deng.qiya.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import deng.qiya.model.CheckCode;
import deng.qiya.model.CrsStRoomType;
import deng.qiya.util.CustomerContextHolder;
import deng.qiya.wechat.Constant;

public class CheckCodeOper {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public CheckCode getCheckCodeByPhone(String phone){
		String sql = "SELECT TOP 1 [ID]      ,[PHONE]      ,[CODE]      ,[EXPIRED_TIME]      ,[SYSTEM_TIME]  FROM [CHECK_CODE] WHERE [EXPIRED_TIME] > DATEADD(day,-1,GETDATE()) AND PHONE = ? ORDER BY SYSTEM_TIME DESC";
		CustomerContextHolder.setCustomerType(Constant.ds);
		Object[] args = new Object[]{phone};
		List<CheckCode> list =jdbcTemplate.query(sql, args, new CheckCodeMapper());
		if(list != null && list.size()>0){
			return list.get(0);
		}
		else{
		return null;
		}
	}
	
	public  List<CrsStRoomType> getCrsStRoomType()
	{
		String sql=" select * from Crs_StRoomType ";
		CustomerContextHolder.setCustomerType(Constant.dscrs);
		List<CrsStRoomType> list=null;
		try
		{
			list=jdbcTemplate.query(sql, new CrsStRoomTypeMapper());
		}catch(Exception e)
		{
			
			e.printStackTrace();
		}
		
		
		return list;
		
	}
	
	public int newCheckCode(CheckCode checkCode){
		String sql = "INSERT INTO [CHECK_CODE]           ([PHONE]           ,[CODE]           ,[EXPIRED_TIME]           ,[SYSTEM_TIME])     VALUES" +
				"(?,?,?,?)";
		CustomerContextHolder.setCustomerType(Constant.ds);
		Object[] args = new Object[]{
				checkCode.getPhone(),
				checkCode.getCode(),
				checkCode.getExpiredTime(),
				checkCode.getSystemTime()
		};
		jdbcTemplate.update(sql,args);
		return jdbcTemplate.queryForInt( "select @@identity" );
	}
	
	class CheckCodeMapper implements RowMapper<CheckCode>{

		@Override
		public CheckCode mapRow(ResultSet rs, int rowNum) throws SQLException {
			CheckCode cc =new CheckCode();
			cc.setId(rs.getInt("ID"));
			cc.setExpiredTime(rs.getTimestamp("EXPIRED_TIME"));
			cc.setCode(rs.getString("CODE"));
			cc.setPhone(rs.getString("PHONE"));
			cc.setSystemTime(rs.getTimestamp("SYSTEM_TIME"));
			return cc;
		}
		
	}
	
	class CrsStRoomTypeMapper implements RowMapper<CrsStRoomType>{

		@Override
		public CrsStRoomType mapRow(ResultSet rs, int rowNum) throws SQLException {
			CrsStRoomType rm =new CrsStRoomType();
			rm.setId(rs.getInt("id"));
			rm.setRmTypeCd(rs.getString("RmTypeCd"));
			rm.setRmTypeDesp(rs.getString("RmTypeDesp"));
			rm.setRmTypeDesp_En(rs.getString("RmTypeDesp_En"));
			rm.setMastRmType(rs.getString("MastRmType"));
			rm.setDesp(rs.getString("Desp"));
			return rm;
		}
		
	}
}
